<template>
  <view class="news-manage-container">
    <!-- 头部操作栏 -->
    <view class="operation-header">
      <uni-search-bar 
        placeholder="搜索资讯标题或内容" 
        v-model="searchKey"
        @confirm="loadData(true)"
        cancel-button="none"
      ></uni-search-bar>
      <view class="header-actions">
        <picker @change="statusFilterChange" :value="filterStatus" :range="statusOptions">
          <view class="filter-btn">
            {{ statusOptions[filterStatus] }}
            <uni-icons type="arrowdown" size="14" color="#666"></uni-icons>
          </view>
        </picker>
        <button class="add-btn" @tap="showEditPopup(null)">+ 新增资讯</button>
      </view>
    </view>

    <!-- 数据统计 -->
    <scroll-view class="stats-bar" scroll-x>
      <view class="stats-item">
        <text class="stats-value">{{ total }}</text>
        <text class="stats-label">总资讯数</text>
      </view>
      <view class="stats-item">
        <text class="stats-value">{{ publishedCount }}</text>
        <text class="stats-label">已发布</text>
      </view>
      <view class="stats-item">
        <text class="stats-value">{{ draftCount }}</text>
        <text class="stats-label">草稿</text>
      </view>
    </scroll-view>

    <!-- 资讯列表 -->
    <scroll-view 
      class="news-list"
      scroll-y
      @scrolltolower="loadMore"
    >
      <view 
        v-for="item in showList"
        :key="item.id"
        class="news-card"
      >
        <image 
          class="cover"
          :src="item.cover || defaultCover"
          mode="aspectFill"
          @tap="previewCover(item.cover)"
        ></image>
        <view class="content">
          <view class="meta">
            <text class="title">{{ item.title }}</text>
            <uni-tag 
              :text="item.status | statusText"
              :type="item.status | statusType"
              size="small"
              custom-style="margin-left:10rpx;"
            />
          </view>
          <text class="category">{{ item.category }}</text>
          <view class="footer">
            <text class="time">{{ item.createTime | formatTime }}</text>
            <view class="actions">
              <button class="btn edit" @tap="showEditPopup(item)">编辑</button>
              <button 
                class="btn toggle-status"
                :class="item.status ? 'unpublish' : 'publish'"
                @tap="toggleStatus(item)"
              >
                {{ item.status ? '下架' : '发布' }}
              </button>
              <button 
                class="btn delete"
                @tap="deleteNews(item)"
                v-if="adminInfo.role === '超级管理员'"
              >删除</button>
            </view>
          </view>
        </view>
      </view>

      <uni-load-more 
        :status="loadingStatus"
        :content-text="{
          contentdown: '上拉加载更多',
          contentrefresh: '正在加载...',
          contentnomore: '没有更多了'
        }"
      ></uni-load-more>
    </scroll-view>

    <!-- 编辑弹窗 -->
    <uni-popup ref="editPopup" type="dialog">
      <uni-popup-dialog 
        mode="form"
        :title="editForm.id ? '编辑资讯' : '新增资讯'"
        @confirm="submitForm"
      >
        <uni-forms :model="editForm">
          <uni-forms-item label="资讯标题" required>
            <uni-easyinput v-model="editForm.title" placeholder="请输入标题" />
          </uni-forms-item>
          <!-- <uni-forms-item label="分类" required>
            <uni-data-select
              v-model="editForm.category"
              :localdata="categories"
            ></uni-data-select>
          </uni-forms-item> -->
          <uni-forms-item label="封面图">
            <uni-file-picker 
              v-model="editForm.cover"
              fileMediatype="image"
              limit="1"
              :imageStyles="{width: '200rpx', height: '200rpx'}"
            ></uni-file-picker>
          </uni-forms-item>
          <uni-forms-item label="资讯内容" required>
            <uni-easyinput 
              type="textarea"
              v-model="editForm.content" 
              placeholder="请输入内容"
              :styles="{height:'300rpx'}"
            />
          </uni-forms-item>
        </uni-forms>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
const generateNews = (() => {
  let id = 0
  const categories = ['行业动态', '政策解读', '技术前沿', '活动通知']
  return () => ({
    id: ++id,
    title: `资讯标题示例${id}`,
    content: `这里是资讯内容示例，包含行业最新动态和技术发展趋势说明...${id}`,
    category: categories[Math.floor(Math.random()*4)],
    cover: Math.random() > 0.3 ? `https://picsum.photos/300/200?random=${id}` : '',
    status: Math.random() > 0.5 ? 1 : 0,
    createTime: Date.now() - Math.floor(Math.random()*30*86400000)
  })
})()

export default {
  data() {
    return {
      adminInfo: {
        role: '超级管理员'
      },
      searchKey: '',
      filterStatus: 0,
      statusOptions: ['全部状态', '已发布', '草稿'],
      loadingStatus: 'more',
      page: 1,
      pageSize: 10,
      newsList: Array.from({length: 15}, generateNews),
      editForm: {
        id: null,
        title: '',
        category: '',
        content: '',
        cover: ''
      },
      categories: [
        { value: '行业动态', text: '行业动态' },
        { value: '政策解读', text: '政策解读' },
        { value: '技术前沿', text: '技术前沿' },
        { value: '活动通知', text: '活动通知' }
      ],
      defaultCover: 'https://mp-1de2ab47-60cc-4717-bb0c-985e43d6d68e.cdn.bspapp.com/img/default-news.png'
    }
  },
  computed: {
    total() {
      return this.newsList.length
    },
    publishedCount() {
      return this.newsList.filter(n => n.status).length
    },
    draftCount() {
      return this.newsList.filter(n => !n.status).length
    },
    showList() {
      return this.newsList
        .filter(item => {
          // 状态筛选
          if(this.filterStatus === 1 && !item.status) return false
          if(this.filterStatus === 2 && item.status) return false
          
          // 关键词搜索
          const key = this.searchKey.toLowerCase()
          return (
            item.title.toLowerCase().includes(key) ||
            item.content.toLowerCase().includes(key)
          )
        })
        .slice(0, this.page * this.pageSize)
    }
  },
  filters: {
    statusText(status) {
      return status ? '已发布' : '草稿'
    },
    statusType(status) {
      return status ? 'success' : 'warning'
    },
    formatTime(timestamp) {
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`
    }
  },
  methods: {
    statusFilterChange(e) {
      this.filterStatus = e.detail.value
      this.page = 1
    },
    loadData(reset = false) {
      if(reset) this.page = 1
      // 模拟加载数据
      setTimeout(() => {
        if(this.page === 1) this.newsList = Array.from({length: 15}, generateNews)
        this.loadingStatus = this.page * this.pageSize >= 30 ? 'noMore' : 'more'
      }, 800)
    },
    loadMore() {
      if(this.loadingStatus !== 'more') return
      this.page++
      this.loadData()
    },
    showEditPopup(item) {
      this.editForm = item ? {...item} : {
        id: null,
        title: '',
        category: '',
        content: '',
        cover: ''
      }
      this.$refs.editPopup.open()
    },
    submitForm() {
      if(!this.validateForm()) return
      
      if(this.editForm.id) {
        const index = this.newsList.findIndex(n => n.id === this.editForm.id)
        this.newsList.splice(index, 1, this.editForm)
      } else {
        this.newsList.unshift({
          ...this.editForm,
          id: Date.now(),
          createTime: Date.now(),
          status: 0
        })
      }
      this.$refs.editPopup.close()
      uni.showToast({ title: '操作成功' })
    },
    validateForm() {
      if(!this.editForm.title.trim()) {
        uni.showToast({ title: '请输入标题', icon: 'none' })
        return false
      }
      if(!this.editForm.category) {
        uni.showToast({ title: '请选择分类', icon: 'none' })
        return false
      }
      if(!this.editForm.content.trim()) {
        uni.showToast({ title: '请输入内容', icon: 'none' })
        return false
      }
      return true
    },
    toggleStatus(item) {
      item.status = !item.status
      uni.showToast({ title: item.status ? '已发布' : '转为草稿' })
    },
    deleteNews(item) {
      uni.showModal({
        title: '确认删除',
        content: '确定要永久删除该资讯吗？',
        success: (res) => {
          if(res.confirm) {
            this.newsList = this.newsList.filter(n => n.id !== item.id)
          }
        }
      })
    },
    previewCover(url) {
      if(!url) return
      uni.previewImage({
        urls: [url],
        indicator: 'default'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.news-manage-container {
  padding: 30rpx;
  background: #f5f7fa;
  min-height: 100vh;
}

.operation-header {
  background: white;
  padding: 30rpx;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);

  .header-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30rpx;

    .filter-btn {
      padding: 12rpx 30rpx;
      background: #f8f9fa;
      border-radius: 8rpx;
      font-size: 28rpx;
      color: #666;
    }

    .add-btn {
      padding: 12rpx 30rpx;
      background: #3498db;
      color: white;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
  }
}

.stats-bar {
  white-space: nowrap;
  margin-bottom: 30rpx;

  .stats-item {
    display: inline-block;
    background: white;
    padding: 30rpx 50rpx;
    border-radius: 16rpx;
    margin-right: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);

    .stats-value {
      font-size: 40rpx;
      font-weight: bold;
      color: #2ecc71;
      margin-right: 15rpx;
    }

    .stats-label {
      font-size: 28rpx;
      color: #7f8c8d;
    }
  }
}

.news-list {
  height: calc(100vh - 400rpx);
}

.news-card {
  display: flex;
  background: white;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
  overflow: hidden;

  .cover {
    width: 250rpx;
    height: 200rpx;
    background: #f0f0f0;
  }

  .content {
    flex: 1;
    padding: 30rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .meta {
      display: flex;
      align-items: center;
      margin-bottom: 15rpx;

      .title {
        font-size: 32rpx;
        font-weight: 500;
        color: #2c3e50;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
    }

    .category {
      font-size: 26rpx;
      color: #3498db;
      background: #e8f4ff;
      padding: 6rpx 15rpx;
      border-radius: 6rpx;
      align-self: flex-start;
    }

    .footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20rpx;

      .time {
        font-size: 24rpx;
        color: #95a5a6;
      }

      .actions {
        display: flex;
        gap: 15rpx;

        .btn {
          padding: 8rpx 25rpx;
          font-size: 24rpx;
          border-radius: 6rpx;

          &.edit {
            background: #f1c40f;
            color: white;
          }
          &.publish {
            background: #2ecc71;
            color: white;
          }
          &.unpublish {
            background: #e74c3c;
            color: white;
          }
          &.delete {
            background: #95a5a6;
            color: white;
          }
        }
      }
    }
  }
}

::v-deep .uni-forms-item__label {
  font-weight: bold;
  color: #34495e !important;
}
</style>